package com.breadenglish.cms.api.app.gateway.util.concurrent;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;

public class IdelCalculator {
    public long maxIdel;
    public long lastIdel;
    public long avgIdel;
    public long minIdel = Long.MAX_VALUE;
    public long requestTimes;
    public long sumIdel;
    private long time;
    private boolean isStart = false;
    private long toFileTimeTemp = 0;

    synchronized public void start() {
        isStart = true;
        time = System.currentTimeMillis();
    }

    synchronized public void end() {
        if (isStart)
            isStart = false;
        else
            return;
        time = System.currentTimeMillis() - time;
        requestTimes++;
        sumIdel += time;
        maxIdel = time > maxIdel ? time : maxIdel;
        minIdel = time < minIdel ? time : minIdel;
        lastIdel = time;
        avgIdel = sumIdel / requestTimes;
    }

    public String toString() {
        return " 最大用时：" + maxIdel + " 最后一次用时：" + lastIdel + " 平均用时：" + avgIdel
                + " 最小用时：" + minIdel + " 运行次数" + requestTimes + " 总用时："
                + sumIdel;
    }

    public void toFile(String fileName, long time) {
        try {
            if (System.currentTimeMillis() - toFileTimeTemp > time) {
                FileWriter fw = new FileWriter(fileName);
                fw.write(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        .format(new java.util.Date())
                        + "\t"
                        + toString()
                        + "\r\n");
                fw.close();
                time = System.currentTimeMillis();
            }
        } catch (IOException e) {
            System.out
                    .println(this.getClass().getName() + ":" + e.getMessage());
        }
    }
}
